import { computed, reactive, ref, watch } from 'vue'
import { goTo } from '@/utils/navigation.js'
import http from '../utils/http.js'

const API_PATHS = {
  GET_PAPER_LABEL_STUDENTS: '/jsonrest/mobile/student/PaperLabelStudent/0/getPaperLabelStudents'
}

const DEFAULT_QUERY = {
  pageSize: 5,
  currentPage: 1,
  type: undefined,
  labelName: ''
}

export const getPaperLabelStudents = (params = {}) => {
  const query = {
    ...DEFAULT_QUERY,
    ...params
  }

  const requestParams = {
    'searchVPaperLabelStudentVO.pageSize': query.pageSize,
    'searchVPaperLabelStudentVO.currentPage': query.currentPage
  }

  if (query.type !== undefined && query.type !== null && query.type !== '') {
    requestParams['searchVPaperLabelStudentVO.type'] = query.type
  }

  const keyword = typeof query.labelName === 'string' ? query.labelName.trim() : ''
  if (keyword) {
    requestParams['searchVPaperLabelStudentVO.label_name'] = keyword
  }

  return http.get(API_PATHS.GET_PAPER_LABEL_STUDENTS, requestParams)
}

const FILTER_TYPE_MAP = {
  '': undefined,
  '1': 1,
  '2': 2,
  '3': 3
}

const FILTER_OPTIONS = [
  { value: '', label: '全部类型' },
  { value: '1', label: '单元测试' },
  { value: '2', label: '统考联考' },
  { value: '3', label: '校内考试' }
]

const ICON_MAP = {
  1: 'https://donglem.oss-cn-hangzhou.aliyuncs.com/client/we_chat/单元考试.png',
  2: 'https://donglem.oss-cn-hangzhou.aliyuncs.com/client/we_chat/统考联考.png',
  3: 'https://donglem.oss-cn-hangzhou.aliyuncs.com/client/we_chat/校内考试.png'
}

const TYPE_LABEL_MAP = {
  1: '单元测试',
  2: '统考联考',
  3: '校内考试'
}

const mapExamItem = (item) => ({
  id: item.id || `${item.label_id || ''}_${item.exam_id || ''}`,
  title: item.label_name || '未命名考试',
  date: item.exam_time || '',
  type: item.type,
  typeLabel: TYPE_LABEL_MAP[item.type] || '',
  iconImg: ICON_MAP[item.type] || 'https://donglem.oss-cn-hangzhou.aliyuncs.com/client/we_chat/统考联考.png',
  raw: item
})

export const useLearningStatus = ({ api, userUtils }) => {
  const statusBarHeight = ref(0)

  const userInfo = ref({
    name: '',
    school: '',
    grade: '',
    class: '',
    avatar: ''
  })

  const showDropdown = ref(false)
  const currentFilter = ref('')
  const searchKeyword = ref('')

  const examRawList = ref([])
  const examList = computed(() => examRawList.value.map(mapExamItem))

  const waterfallColumns = ref([[]])

  const rebuildWaterfall = (list = []) => {
    waterfallColumns.value = [list]
  }

  const loadingState = reactive({
    refreshing: false,
    loadingMore: false,
    finished: false
  })

  const pagination = reactive({
    pageSize: 5,
    currentPage: 1
  })

  const filterParams = reactive({
    type: undefined,
    keyword: ''
  })

  const filterLabel = computed(() => {
    const option = FILTER_OPTIONS.find(item => item.value === currentFilter.value)
    return option ? option.label : '考试类型'
  })

  const toggleDropdown = () => {
    showDropdown.value = !showDropdown.value
  }

  const loadExamList = async (mode = 'refresh') => {
    if (mode === 'refresh') {
      if (loadingState.refreshing) return
    } else if (loadingState.loadingMore || loadingState.finished) {
      return
    }

    try {
      if (mode === 'refresh') {
        loadingState.refreshing = true
        loadingState.finished = false
        pagination.currentPage = 1
      } else {
        loadingState.loadingMore = true
        pagination.currentPage += 1
      }

      const response = await getPaperLabelStudents({
        pageSize: pagination.pageSize,
        currentPage: pagination.currentPage,
        type: filterParams.type,
        labelName: filterParams.keyword
      })

      console.log('学情标签学生数据:', response)

      const list = Array.isArray(response?.entity?.resultList)
        ? response.entity.resultList
        : []

      if (mode === 'refresh') {
        examRawList.value = list
      } else {
        examRawList.value = [...examRawList.value, ...list]
      }

      rebuildWaterfall(examList.value)

      const totalCount = response?.entity?.totalCount
      const loadedCount = pagination.currentPage * pagination.pageSize
      const hasValidTotal = typeof totalCount === 'number' && totalCount >= 0
      const noMoreByTotal = hasValidTotal ? loadedCount >= totalCount : false
      const noMoreBySize = list.length < pagination.pageSize
      loadingState.finished = noMoreByTotal || noMoreBySize
    } catch (error) {
      if (mode === 'loadMore') {
        pagination.currentPage = Math.max(1, pagination.currentPage - 1)
      }
      console.error('获取学情标签学生数据失败:', error)
    } finally {
      loadingState.refreshing = false
      loadingState.loadingMore = false
    }
  }

  const selectFilter = async (value) => {
    if (currentFilter.value === value) {
      showDropdown.value = false
      return
    }
    currentFilter.value = value
    filterParams.type = FILTER_TYPE_MAP[value]
    resetPagination()
    await loadExamList('refresh')
    showDropdown.value = false
  }

  const handleSearch = async () => {
    if (loadingState.refreshing || loadingState.loadingMore) {
      return
    }
    filterParams.keyword = searchKeyword.value.trim()
    resetPagination()
    await loadExamList('refresh')
  }

  const resetPagination = () => {
    pagination.currentPage = 1
    loadingState.finished = false
  }

  const handlePullDownRefresh = async () => {
    resetPagination()
    await loadExamList('refresh')
    uni.stopPullDownRefresh()
  }

  const goToScoreCompare = () => {
    goTo('/subpackages/learning-analysis/scoreCompare')
  }

  const viewExamDetail = ({ examId, examType, courseId } = {}) => {
    const query = []
    if (examId !== undefined && examId !== null && `${examId}`.trim() !== '') {
      query.push(`examId=${encodeURIComponent(examId)}`)
    }
    if (examType !== undefined && examType !== null && `${examType}`.trim() !== '') {
      query.push(`examType=${encodeURIComponent(examType)}`)
    }
    if (courseId !== undefined && courseId !== null && `${courseId}`.trim() !== '') {
      query.push(`courseId=${encodeURIComponent(courseId)}`)
    }

    const queryString = query.length ? `?${query.join('&')}` : ''

    goTo(`/subpackages/learning-analysis/checkLearningStatus${queryString}`)
  }

  const syncUserInfoFromStorage = () => {
    const storedInfo = userUtils?.getUserInfo?.()
    if (storedInfo) {
      userInfo.value = {
        ...userInfo.value,
        name: storedInfo.userName || userInfo.value.name,
        school: storedInfo.dictName || userInfo.value.school,
        grade: storedInfo.grade_name || uni.getStorageSync('gradeName') || userInfo.value.grade,
        class: storedInfo.class_name || uni.getStorageSync('className') || userInfo.value.class,
        avatar: storedInfo.user_avatar || userInfo.value.avatar || '/static/avatar.png'
      }
    }
  }

  const fetchUserInfo = async () => {
    try {
      const response = await api?.user.getUserInfo()
      console.log('学情页用户信息:', response)
      if (response?.entity) {
        userUtils?.saveUserInfo(response.entity)
        userInfo.value = {
          ...userInfo.value,
          name: response.entity.userName || userInfo.value.name,
          school: response.entity.dictName || userInfo.value.school,
          grade: response.entity.grade_name || userInfo.value.grade,
          class: response.entity.class_name || userInfo.value.class,
          avatar: response.entity.user_avatar || userInfo.value.avatar || '/static/avatar.png'
        }
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  const initPage = async () => {
    const systemInfo = uni.getSystemInfoSync()
    statusBarHeight.value = systemInfo.statusBarHeight || 0

    syncUserInfoFromStorage()

    await loadExamList('refresh')
  }

  const handleReachBottom = async () => {
    await loadExamList('loadMore')
  }

  watch(examList, (list) => {
    rebuildWaterfall(list)
  }, { immediate: true })

  return {
    statusBarHeight,
    userInfo,
    showDropdown,
    currentFilter,
    searchKeyword,
    examList,
    waterfallColumns,
    loadingState,
    pagination,
    filterParams,
    filterOptions: FILTER_OPTIONS,
    filterLabel,
    toggleDropdown,
    selectFilter,
    handleSearch,
    handlePullDownRefresh,
    goToScoreCompare,
    viewExamDetail,
    initPage,
    handleReachBottom,
    fetchUserInfo
  }
}

const LearningStatusApi = {
  getPaperLabelStudents
}

export default LearningStatusApi
export {
  FILTER_OPTIONS,
  FILTER_TYPE_MAP,
  ICON_MAP,
  TYPE_LABEL_MAP
}
